<template>
  <div class="app-container">


    <!-- Success Message View -->
    <el-card v-if="showSuccessMessage" shadow="hover" class="success-card">
      <el-result
        icon="success"
        title="已成功入住"
        :sub-title="`将在 ${countdown} 秒后自动返回列表页`"
      >
        <template #extra>
           <el-progress type="circle" :percentage="countdownPercentage" :width="80">
             <span style="font-size: 24px;">{{ countdown }}</span>
           </el-progress>
           <div style="margin-top: 20px;">
             <el-button type="primary" @click="handleReturnToList">立即返回列表</el-button>
           </div>
        </template>
      </el-result>
    </el-card>

    <!-- Main Admission Process View (Hide when success message is shown) -->
    <el-card v-else shadow="hover">
      <template #header>
        <div class="card-header">
          <span>客户入住流程</span>
          <div class="right-buttons">
            <el-button v-if="activeStep > 0" type="primary" plain @click="prevStep">上一步</el-button>
            <el-button v-if="activeStep < steps.length - 1" type="primary" @click="nextStep">下一步</el-button>
            <el-button v-if="activeStep === steps.length - 1" type="success" @click="submitForm">提交</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </div>
      </template>

      <!-- Add Progress Bar -->
      <el-progress :percentage="progressPercentage" :text-inside="true" :stroke-width="20" status="success" style="margin: 15px 0;" />

      <!-- 步骤条 -->
      <el-steps :active="activeStep" finish-status="success" class="mb-4">
        <el-step v-for="(step, index) in steps" :key="index" :title="step.title" :description="step.description" />
      </el-steps>

      <!-- 步骤内容区域 -->
      <div class="step-content">
        <!-- 步骤1：基本信息 -->
        <div v-show="activeStep === 0">
          <el-alert
            type="info"
            title="请先选择一位老人进行入住"
            description="如果没有找到需要的老人信息，请先在老人基础信息管理中添加"
            show-icon
            :closable="false"
            class="mb-4"
          />

          <el-row :gutter="20" class="mb-4">
            <el-col :span="18">
              <el-input
                v-model="elderSearchKeyword"
                placeholder="输入老人姓名或身份证号搜索"
                clearable
                @keyup.enter="searchElder"
              >
                <template #append>
                  <el-button @click="searchElder">
                    <el-icon><search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="searchElder">搜索</el-button>
              <el-button type="success" @click="goToElderManagement">添加老人</el-button>
            </el-col>
          </el-row>

          <el-table
            v-loading="elderLoading"
            :data="elderList"
            border
            highlight-current-row
            @row-click="handleElderSelect"
            style="width: 100%"
          >
            <el-table-column type="index" width="50" />
            <el-table-column label="姓名" prop="elderName" min-width="100" />
            <el-table-column label="性别" prop="gender" min-width="60">
              <template #default="scope">
                {{ scope.row.gender === 0 ? '男' : scope.row.gender === 1 ? '女' : '未知' }}
              </template>
            </el-table-column>
            <el-table-column label="身份证号" prop="idCard" min-width="150" />
            <el-table-column label="年龄" prop="age" min-width="60" />
            <el-table-column label="联系电话" prop="phone" min-width="120" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button link type="primary" @click.stop="handleElderSelect(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-if="elderList.length > 0"
            class="mt-2"
            layout="total, sizes, prev, pager, next"
            :total="elderTotal"
            :page-size="elderQuery.pageSize"
            :current-page="elderQuery.pageNum"
            @size-change="handleElderSizeChange"
            @current-change="handleElderCurrentChange"
          />

          <!-- 已选老人信息卡片 -->
          <el-card v-if="selectedElder" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>已选老人信息</span>
                <el-button link type="danger" @click="clearSelectedElder">取消选择</el-button>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="姓名">{{ selectedElder.elderName }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ selectedElder.gender === 0 ? '男' : selectedElder.gender === 1 ? '女' : '未知' }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ selectedElder.idCard }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ selectedElder.age }}</el-descriptions-item>
              <el-descriptions-item label="家庭地址" :span="2">{{ selectedElder.addressDetail || '未填写' }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>

        <!-- 步骤2：联系人信息 -->
        <div v-show="activeStep === 1">
          <el-alert
            type="info"
            title="请选择一位联系人"
            description="如果没有找到需要的联系人信息，请先在联系人管理中添加"
            show-icon
            :closable="false"
            class="mb-4"
          />

          <el-row :gutter="20" class="mb-4">
            <el-col :span="18">
              <el-input
                v-model="contactSearchKeyword"
                placeholder="输入联系人姓名或电话搜索"
                clearable
                @keyup.enter="searchContact"
              >
                <template #append>
                  <el-button @click="searchContact">
                    <el-icon><search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="searchContact">搜索</el-button>
              <el-button type="success" @click="goToContactManagement">添加联系人</el-button>
            </el-col>
          </el-row>

          <el-table
            v-loading="contactLoading"
            :data="contactList"
            border
            highlight-current-row
            @row-click="handleContactSelect"
            style="width: 100%"
          >
            <el-table-column type="index" width="50" />
            <el-table-column label="姓名" prop="contactName" min-width="100" />
            <el-table-column label="电话" prop="phone" min-width="120" />
            <el-table-column label="与老人关系" prop="relationship" min-width="100" />
            <el-table-column label="是否紧急联系人" prop="isEmergencyContact" min-width="120">
              <template #default="scope">
                {{ scope.row.isEmergencyContact === 1 ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button link type="primary" @click.stop="handleContactSelect(scope.row)">选择</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-if="contactList.length > 0"
            class="mt-2"
            layout="total, sizes, prev, pager, next"
            :total="contactTotal"
            :page-size="contactQuery.pageSize"
            :current-page="contactQuery.pageNum"
            @size-change="handleContactSizeChange"
            @current-change="handleContactCurrentChange"
          />

          <!-- 已选联系人信息卡片 -->
          <el-card v-if="selectedContact" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>已选联系人信息</span>
                <el-button link type="danger" @click="clearSelectedContact">取消选择</el-button>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="姓名">{{ selectedContact.contactName }}</el-descriptions-item>
              <el-descriptions-item label="电话">{{ selectedContact.phone }}</el-descriptions-item>
              <el-descriptions-item label="与老人关系">{{ selectedContact.relationship }}</el-descriptions-item>
              <el-descriptions-item label="是否紧急联系人">{{ selectedContact.isEmergencyContact === 1 ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="联系人地址" :span="2">{{ selectedContact.address || '未填写' }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>

        <!-- 步骤3：入住信息 -->
        <div v-show="activeStep === 2">
          <el-form ref="admissionInfoFormRef" :model="formData" :rules="admissionInfoRules" label-width="120px">
            <div class="form-section-title">合同基本信息</div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractNo">
                  <el-input v-model="formData.contractNo" placeholder="合同编号将自动生成" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入住日期" prop="startDate">
                  <el-date-picker
                    v-model="formData.startDate"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择入住日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预计结束日期" prop="endDate">
                  <el-date-picker
                    v-model="formData.endDate"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择预计结束日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同类型" prop="contractType">
                  <el-select v-model="formData.contractType" placeholder="请选择合同类型" style="width: 100%">
                    <el-option v-for="dict in sys_contract_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="form-section-title">房间与床位信息</div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="房间号" prop="roomId">
                  <el-select
                    v-model="formData.roomId"
                    placeholder="请选择房间号"
                    style="width: 100%"
                    @change="handleRoomChange"
                    :loading="roomLoading"
                  >
                    <el-option
                      v-for="room in roomList"
                      :key="room.roomId"
                      :label="getRoomDisplay(room)"
                      :value="room.roomId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="床位号" prop="bedNumber">
                  <el-select
                    v-model="formData.bedNumber"
                    placeholder="请选择床位号"
                    style="width: 100%"
                    :loading="bedLoading"
                    :disabled="!formData.roomId"
                  >
                    <el-option
                      v-for="bed in bedList"
                      :key="bed.bedId"
                      :label="bed.bedNumber"
                      :value="bed.bedNumber"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="护理等级" prop="careLevel">
                  <el-select v-model="formData.careLevel" placeholder="请选择护理等级" style="width: 100%">
                    <el-option label="一级护理" value="一级护理" />
                    <el-option label="二级护理" value="二级护理" />
                    <el-option label="三级护理" value="三级护理" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 步骤4：费用信息 -->
        <div v-show="activeStep === 3">
          <el-form ref="feeInfoFormRef" :model="formData" :rules="feeInfoRules" label-width="120px">
            <div class="form-section-title">费用金额信息</div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="月费用" prop="monthlyFee">
                  <el-input-number v-model="formData.monthlyFee" :min="0" :precision="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="押金" prop="deposit">
                  <el-input-number v-model="formData.deposit" :min="0" :precision="0" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="付款周期" prop="paymentCycle">
                  <el-select v-model="formData.paymentCycle" placeholder="请选择付款周期" style="width: 100%">
                    <el-option label="月付" value="月付" />
                    <el-option label="季付" value="季付" />
                    <el-option label="半年付" value="半年付" />
                    <el-option label="年付" value="年付" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="费用类型" prop="feeType">
                  <el-select v-model="formData.feeType" placeholder="请选择费用类型" style="width: 100%">
                    <el-option
                      v-for="dict in sys_fee_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="form-section-title">支付信息</div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="支付方式" prop="paymentMethod">
                  <el-select v-model="formData.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
                    <el-option
                      v-for="dict in sys_payment_method"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付状态" prop="paymentStatus">
                  <el-select v-model="formData.paymentStatus" placeholder="请选择支付状态" style="width: 100%">
                    <el-option
                      v-for="dict in payment_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>
        </div>

        <!-- 步骤5：确认信息 -->
        <div v-show="activeStep === 4">
          <div class="confirm-container">
            <!-- 老人基本信息 -->
            <div class="form-section-title">老人基本信息</div>
            <el-descriptions :column="2" border size="default" class="mb-4">
              <el-descriptions-item label="老人姓名">{{ formData.elderName }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ formData.gender === 0 ? '男' : formData.gender === 1 ? '女' : '未知' }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ formData.idCard }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ formData.phone }}</el-descriptions-item>
            </el-descriptions>

            <!-- 联系人信息 -->
            <div class="form-section-title">联系人信息</div>
            <el-descriptions :column="2" border size="default" class="mb-4">
              <el-descriptions-item label="联系人姓名">{{ formData.contactName }}</el-descriptions-item>
              <el-descriptions-item label="联系人电话">{{ formData.contactPhone }}</el-descriptions-item>
              <el-descriptions-item label="与老人关系">{{ formData.relationship }}</el-descriptions-item>
              <el-descriptions-item label="联系人地址">{{ formData.contactAddress || '未填写' }}</el-descriptions-item>
            </el-descriptions>

            <!-- 合同信息 -->
            <div class="form-section-title">合同信息</div>
            <el-descriptions :column="2" border size="default" class="mb-4">
              <el-descriptions-item label="合同编号">{{ formData.contractNo }}</el-descriptions-item>
              <el-descriptions-item label="合同类型">{{ formData.contractType }}</el-descriptions-item>
              <el-descriptions-item label="入住日期">{{ formData.startDate ? formData.startDate.split(' ')[0] : '' }}</el-descriptions-item>
              <el-descriptions-item label="预计结束日期">{{ formData.endDate ? formData.endDate.split(' ')[0] : '' }}</el-descriptions-item>
            </el-descriptions>

            <!-- 房间信息 -->
            <div class="form-section-title">房间与护理信息</div>
            <el-descriptions :column="2" border size="default" class="mb-4">
              <el-descriptions-item label="房间号">{{ getRoomNumberById(formData.roomId) }}</el-descriptions-item>
              <el-descriptions-item label="床位号">{{ formData.bedNumber }}</el-descriptions-item>
              <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
              <el-descriptions-item label="护理说明">根据护理等级提供相应的照护服务</el-descriptions-item>
            </el-descriptions>

            <!-- 费用信息 -->
            <div class="form-section-title">费用信息</div>
            <el-descriptions :column="2" border size="default" class="mb-4">
              <el-descriptions-item label="费用类型">{{ formData.feeType }}</el-descriptions-item>
              <el-descriptions-item label="月费用">{{ formData.monthlyFee }} 元</el-descriptions-item>
              <el-descriptions-item label="押金">{{ formData.deposit }} 元</el-descriptions-item>
              <el-descriptions-item label="付款周期">{{ formData.paymentCycle }}</el-descriptions-item>
              <el-descriptions-item label="支付方式">{{ formData.paymentMethod }}</el-descriptions-item>
              <el-descriptions-item label="支付状态">{{ formData.paymentStatus }}</el-descriptions-item>
            </el-descriptions>

            <!-- 签约人信息 -->
            <div class="form-section-title">签约人信息</div>
            <el-form ref="signerInfoFormRef" :model="formData" label-width="120px" class="mb-4">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="签约人姓名" prop="signedBy">
                    <el-input v-model="formData.signedBy" placeholder="请输入签约人姓名" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="与老人关系" prop="signerRelationship">
                    <el-input v-model="formData.signerRelationship" placeholder="请输入与老人的关系" />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 特殊条款字段 -->
              <el-form-item label="特殊条款" prop="specialTerms">
                <el-input v-model="formData.specialTerms" type="textarea" placeholder="请输入特殊条款内容" :rows="3" />
              </el-form-item>

              <!-- 合同备注字段 -->
              <el-form-item label="合同备注" prop="contractRemarks">
                <el-input v-model="formData.contractRemarks" type="textarea" placeholder="请输入合同备注内容" :rows="3" />
              </el-form-item>
            </el-form>

            <!-- 协议确认 -->
            <div class="form-section-title">协议确认</div>
            <div class="agreement-confirm-box">
              <el-checkbox v-model="formData.agreement">我已确认以上信息无误，并同意相关服务条款</el-checkbox>
              <el-button type="primary" link @click="showAgreementDialog = true">查看服务条款</el-button>
            </div>
          </div>

          <!-- 服务条款对话框 -->
          <el-dialog v-model="showAgreementDialog" title="养老院入住服务协议" width="70%">
            <div class="agreement-content">
              <h2 class="text-center">养老院入住服务协议</h2>
              <p><strong>甲方（养老院）：</strong> 长养乐园养老服务中心</p>
              <p><strong>乙方（入住老人）：</strong> {{ formData.elderName }}</p>
              <p><strong>丙方（老人代理人/联系人）：</strong> {{ formData.contactName }}</p>

              <h3>1. 协议目的</h3>
              <p>本协议旨在明确甲乙双方在养老服务过程中的权利与义务，保障双方的合法权益，建立和谐、有序的养老服务关系。</p>

              <h3>2. 服务内容与标准</h3>
              <p>甲方将为乙方提供包括但不限于以下服务：</p>
              <ul>
                <li>生活照料服务：包括日常起居、饮食、浴室、如厕等基本生活照料。</li>
                <li>医疗护理服务：包括健康检测、用药提醒、简单常见病护理等。</li>
                <li>心理关怀服务：包括心理健康评估、心理疑难疑惑解答等。</li>
                <li>文娱活动服务：包括组织各类文娱活动、节日庆祝活动等。</li>
              </ul>

              <h3>3. 服务期限</h3>
              <p>服务期限自 {{ formData.startDate ? formData.startDate.split(' ')[0] : '' }} 至 {{ formData.endDate ? formData.endDate.split(' ')[0] : '' }}。</p>

              <h3>4. 服务费用及支付方式</h3>
              <p>月费：{{ formData.monthlyFee }}元/月</p>
              <p>押金：{{ formData.deposit }}元</p>
              <p>付款周期：{{ formData.paymentCycle }}</p>
              <p>付款方式：{{ formData.paymentMethod }}</p>

              <h3>5. 双方权利与义务</h3>
              <h4>5.1 甲方权利与义务</h4>
              <p><strong>权利：</strong></p>
              <ul>
                <li>收取服务费用的权利。</li>
                <li>制定并执行养老院的各项规章制度。</li>
                <li>对乙方违反养老院规定的行为进行合理的制止和处理。</li>
              </ul>
              <p><strong>义务：</strong></p>
              <ul>
                <li>提供安全、清洁、舒适的居住环境。</li>
                <li>按照协议约定提供优质的养老服务。</li>
                <li>尊重乙方的人格尊严和隐私权。</li>
                <li>对乙方的健康状况进行定期检查和记录。</li>
              </ul>

              <h4>5.2 乙方权利与义务</h4>
              <p><strong>权利：</strong></p>
              <ul>
                <li>享受甲方提供的各项养老服务。</li>
                <li>对甲方的服务质量提出建议和意见。</li>
                <li>享有人格尊严和隐私保护权。</li>
              </ul>
              <p><strong>义务：</strong></p>
              <ul>
                <li>按时足额缴纳服务费用。</li>
                <li>遵守养老院的各项规章制度。</li>
                <li>尊重工作人员和其他老人。</li>
                <li>爱护养老院设施，不得故意损坏。</li>
              </ul>

              <h3>6. 协议变更与终止</h3>
              <p>本协议经双方协商一致可以变更或终止。如遇下列情况，协议自动终止：</p>
              <ul>
                <li>协议期限届满。</li>
                <li>乙方因病故或其他原因离开养老院。</li>
                <li>乙方违反养老院规定，经教育仍不改正。</li>
                <li>乙方连续三个月未缴纳服务费用。</li>
              </ul>

              <h3>7. 责任与免责条款</h3>
              <p>甲方对因提供服务不当造成的损失承担责任。但对下列情况不承担责任：</p>
              <ul>
                <li>乙方因自身疾病自然发展导致的健康恶化。</li>
                <li>乙方拒绝接受必要的医疗建议和处置。</li>
                <li>不可抗力因素导致的损失。</li>
              </ul>

              <h3>8. 隐私保护</h3>
              <p>甲方承诺对乙方的个人信息予以保密，非经乙方或其代理人同意，不得向第三方透露。</p>

              <h3>9. 争议解决</h3>
              <p>双方如有争议，应先友好协商解决。协商不成的，可向有关部门投诉或向人民法院提起诉讼。</p>

              <h3>10. 其他条款</h3>
              <p>本协议一式两份，甲乙双方各持一份，具有同等法律效力。本协议自双方签字之日起生效。</p>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showAgreementDialog = false">关闭</el-button>
                <el-button type="primary" @click="agreeToTerms">同意协议</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="AdmissionProcess" lang="ts">
import { addAdmissionContract } from '@/api/nursing/admissionContract';
import { listElderBasic, getElderBasic } from '@/api/nursing/elderBasic';
import { listUniqueContactInfo } from '@/api/nursing/contactInfo';
import { getCurrentInstance, reactive, ref, computed, onMounted, onUnmounted, toRefs, nextTick } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { useUserStore } from '@/store/modules/user';
import type { ElForm, FormRules } from 'element-plus';
import type { ElderBasicVO, ElderBasicQuery } from '@/api/nursing/elderBasic/types';
import type { ContactInfoVO, ContactInfoQuery } from '@/api/nursing/contactInfo/types';
import { useRouter } from 'vue-router';
import { listRoomInfo } from '@/api/nursing/roomInfo';
import { listBedInfo } from '@/api/nursing/bedInfo';
import type { RoomInfoVO } from '@/api/nursing/roomInfo/types';
import type { BedInfoVO } from '@/api/nursing/bedInfo/types';

// 使用路由
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_contract_type, sys_fee_type, sys_payment_method, payment_status } = toRefs<any>(proxy?.useDict('sys_contract_type', 'sys_fee_type', 'sys_payment_method', 'payment_status'));

// 判断当前用户是否有管理员角色
const hasAdminRole = () => {
  // 使用useUserStore获取用户角色信息
  const userStore = useUserStore();
  const roles = userStore.roles || [];
  return roles.includes('admin') || roles.includes('admin_ms') || roles.includes('superadmin');
};

// State for success message and countdown
const showSuccessMessage = ref(false);
const countdown = ref(5);
let intervalId: number | null = null;

// 步骤条配置
const steps = [
  { title: '基本信息', description: '老人的基本信息' },
  { title: '联系人信息', description: '紧急联系人信息' },
  { title: '入住信息', description: '入住合同相关信息' },
  { title: '费用信息', description: '费用缴纳信息' },
  { title: '确认信息', description: '确认所有信息' }
];

// 当前激活的步骤
const activeStep = ref(0);

// Computed property for progress bar percentage
const progressPercentage = computed(() => {
  if (steps.length === 0) return 0;
  // Ensure percentage doesn't exceed 100 if somehow activeStep goes beyond last step before submission view
  const currentStepProgress = activeStep.value < steps.length ? activeStep.value + 1 : steps.length;
  return Math.round((currentStepProgress / steps.length) * 100);
});

// 房间相关
const roomList = ref<RoomInfoVO[]>([]);
// 房间可用床位数量映射表 key: roomId, value: "可用床位/总床位"
const roomAvailabilityMap = ref<Record<string, string>>({});
const roomLoading = ref(false);
const bedList = ref<BedInfoVO[]>([]);
const bedLoading = ref(false);

// 老人查询关键字
const elderSearchKeyword = ref('');
// 老人查询加载状态
const elderLoading = ref(false);

// 联系人查询关键字
const contactSearchKeyword = ref('');
// 联系人查询加载状态
const contactLoading = ref(false);
// 老人列表
const elderList = ref<ElderBasicVO[]>([]);
// 老人总数
const elderTotal = ref(0);
// 老人查询参数
const elderQuery = reactive<ElderBasicQuery>({
  pageNum: 1,
  pageSize: 10,
  elderName: undefined,
  idCard: undefined,
  roomNumberIsNull: true // 只查询没有分配房间的老人
});
// 已选择的老人
const selectedElder = ref<ElderBasicVO | null>(null);

// 联系人列表
const contactList = ref<ContactInfoVO[]>([]);
// 联系人总数
const contactTotal = ref(0);
// 联系人查询参数
const contactQuery = reactive<ContactInfoQuery>({
  pageNum: 1,
  pageSize: 10,
  contactName: undefined,
  elderName: undefined
});
// 已选择的联系人
const selectedContact = ref<ContactInfoVO | null>(null);

// 表单引用
const admissionInfoFormRef = ref<InstanceType<typeof ElForm>>();
const feeInfoFormRef = ref<InstanceType<typeof ElForm>>();

// 生成随机合同编号
const generateContractNo = () => {
  const now = new Date();
  const dateStr = now.getFullYear() +
                 String(now.getMonth() + 1).padStart(2, '0') +
                 String(now.getDate()).padStart(2, '0') +
                 String(now.getHours()).padStart(2, '0') +
                 String(now.getMinutes()).padStart(2, '0');

  // 生成随机6位哈希字符串
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let hash = '';
  for (let i = 0; i < 6; i++) {
    hash += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return `${dateStr}-wxx-${hash}`;
};

// 签名相关变量
const showAgreementDialog = ref(false);

// 表单数据
const formData = reactive<any>({
  // 基本信息
  elderId: undefined,
  elderName: '',
  elderPhoto: '',
  gender: 0, // 默认为男性
  birthDate: '',
  age: undefined,
  idCardType: 1,
  idCard: '',
  phone: '',
  addressDetail: '',
  healthStatus: '',

  // 联系人信息
  contactId: undefined,
  contactName: '',
  contactPhone: '',
  relationship: '',
  contactAddress: '',
  isEmergencyContact: 1,
  contactEmail: '',

  // 入住信息
  contractNo: generateContractNo(),
  startDate: '',
  endDate: '',
  roomId: undefined,
  bedNumber: '',
  careLevel: '',
  contractType: '',
  monthlyFee: 0,
  deposit: 0,
  paymentCycle: '',

  // 费用信息
  feeType: undefined, // 将由字典自动设置
  paymentMethod: undefined, // 将由字典自动设置
  paymentStatus: undefined, // 将由字典自动设置

  // 确认信息
  agreement: false,
  signedBy: '',
  signerRelationship: '',
  specialTerms: '', // 添加特殊条款字段
  contractRemarks: '' // 合同备注字段
});

// 表单验证规则
// 移除未使用的验证规则

// 简化入住信息验证规则，只保留入住日期和合同类型为必填项
const admissionInfoRules = reactive<FormRules>({
  contractType: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  roomId: [{ required: true, message: '请选择房间号', trigger: 'change' }],
  bedNumber: [{ required: true, message: '请选择床位号', trigger: 'change' }],
  careLevel: [{ required: true, message: '请选择护理等级', trigger: 'change' }]
});

const feeInfoRules = reactive<FormRules>({
  feeType: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
  paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }],
  monthlyFee: [{ required: true, message: '请输入月费用', trigger: 'blur' }],
  deposit: [{ required: true, message: '请输入押金', trigger: 'blur' }],
  paymentCycle: [{ required: true, message: '请选择付款周期', trigger: 'change' }]
});

// 移除未使用的函数和规则



// 搜索老人
const searchElder = async () => {
  elderLoading.value = true;
  // 设置搜索条件
  if (elderSearchKeyword.value) {
    // 根据关键字判断是身份证还是姓名
    if (/^\d+$/.test(elderSearchKeyword.value)) {
      elderQuery.idCard = elderSearchKeyword.value;
      elderQuery.elderName = undefined;
    } else {
      elderQuery.elderName = elderSearchKeyword.value;
      elderQuery.idCard = undefined;
    }
  } else {
    elderQuery.elderName = undefined;
    elderQuery.idCard = undefined;
  }

  try {
    const res = await listElderBasic(elderQuery);
    elderList.value = res.rows;
    elderTotal.value = res.total;
  } catch (error) {
    console.error('获取老人列表失败', error);
    proxy?.$modal.msgError('获取老人列表失败');
  } finally {
    elderLoading.value = false;
  }
};

// 选择老人
const handleElderSelect = async (elder: ElderBasicVO) => {
  try {
    console.log('选择老人:', elder);
    // 获取老人详情
    const res = await getElderBasic(elder.elderId);
    // 安全的类型转换
    const elderData = res.data as any;

    // 检查老人是否已完成入住流程（房间号不为空）
    if (elderData && elderData.roomNumber) {
      proxy?.$modal.msgWarning('该老人已完成入住流程，房间号为: ' + elderData.roomNumber);
      return;
    }

    // 设置选中的老人
    selectedElder.value = elder;

    // 将老人信息填入表单，确保正确设置elderId
    if (elder.elderId) {
      formData.elderId = typeof elder.elderId === 'string' ? parseInt(elder.elderId, 10) : elder.elderId;
      console.log('设置老人ID:', formData.elderId, '类型:', typeof formData.elderId);
    } else {
      console.warn('选择的老人没有ID');
    }
    formData.elderName = elder.elderName;
    // 确保性别值按照字典正确设置: 0-男, 1-女, 2-未知
    if (elder.gender !== null && elder.gender !== undefined) {
      if (typeof elder.gender === 'string') {
        formData.gender = elder.gender === '0' ? 0 : elder.gender === '1' ? 1 : 2;
      } else if (typeof elder.gender === 'number') {
        formData.gender = [0, 1, 2].includes(elder.gender) ? elder.gender : 0;
      } else {
        formData.gender = 0; // 默认设置为男性
      }
    } else {
      formData.gender = 0; // 默认设置为男性
    }
    formData.birthDate = elder.birthDate;
    formData.age = elder.age;

    // 如果从详情数据中有额外信息，也一并填入
    if (elderData) {
      formData.idCardType = elderData.idCardType || 1;
      formData.idCard = elder.idCard ? String(elder.idCard) : '';
      formData.phone = elderData.phone || '';
      formData.addressDetail = elderData.addressDetail || '';
      formData.healthStatus = elderData.healthStatus || '';
      // 保存老人照片信息
      formData.elderPhoto = elder.elderPhoto || '';
      console.log('设置老人照片:', formData.elderPhoto);

      // 移除自动填充联系人信息的逻辑，避免数据冲突
      // 让用户在联系人步骤中手动选择或填写联系人信息
    }

    proxy?.$modal.msgSuccess('已选择老人: ' + elder.elderName);
  } catch (error) {
    console.error('获取老人详情失败', error);
    proxy?.$modal.msgError('获取老人详情失败');
  }
};

// 清除选中的老人
const clearSelectedElder = () => {
  selectedElder.value = null;
  formData.elderId = undefined;
  resetBasicForm();
};

// 搜索联系人
const searchContact = async () => {
  console.log('开始搜索联系人');
  contactLoading.value = true;
  // 设置搜索条件
  if (contactSearchKeyword.value) {
    // 根据关键字判断是电话还是姓名
    if (/^\d+$/.test(contactSearchKeyword.value)) {
      contactQuery.contactName = undefined;
      // 这里假设有phone字段的查询参数，如果没有需要调整
      contactQuery.elderName = contactSearchKeyword.value;
    } else {
      contactQuery.contactName = contactSearchKeyword.value;
      contactQuery.elderName = undefined;
    }
  } else {
    contactQuery.contactName = undefined;
    // 如果已选择老人，可以默认按老人名称搜索其联系人
    if (formData.elderName && formData.elderId) {
      console.log('按老人名称搜索联系人:', formData.elderName);
      contactQuery.elderName = formData.elderName;
    } else {
      contactQuery.elderName = undefined;
    }
  }

  try {
    console.log('联系人搜索参数:', contactQuery);
    // 使用去重后的联系人列表API
    const res = await listUniqueContactInfo(contactQuery);
    contactList.value = res.data || [];
    contactTotal.value = contactList.value.length;
    console.log('获取到去重后的联系人列表:', contactList.value.length, '条记录');
  } catch (error) {
    console.error('获取联系人列表失败', error);
    proxy?.$modal.msgError('获取联系人列表失败');
  } finally {
    contactLoading.value = false;
  }
};

// 选择联系人
const handleContactSelect = async (contact: ContactInfoVO) => {
  try {
    console.log('选择联系人:', contact);
    // 获取联系人详情 - 不需要获取详情，直接使用传入的contact对象

    // 设置选中的联系人
    selectedContact.value = contact;

    // 将联系人信息填入表单
    formData.contactId = contact.contactId;
    formData.contactName = contact.contactName;
    formData.contactPhone = contact.phone;
    formData.relationship = contact.relationship;
    formData.contactAddress = contact.address || '';
    formData.isEmergencyContact = contact.isEmergencyContact;
    formData.contactEmail = contact.email || '';

    // 确保联系人与老人关联
    if (formData.elderId && contact.elderId && formData.elderId !== contact.elderId) {
      console.log('联系人与老人不匹配，老人 ID:', formData.elderId, '联系人关联的老人 ID:', contact.elderId);
      proxy?.$modal.msgWarning('注意：选择的联系人与当前老人不匹配，但仍然可以使用');
    }

    proxy?.$modal.msgSuccess('已选择联系人: ' + contact.contactName);
  } catch (error) {
    console.error('获取联系人详情失败', error);
    proxy?.$modal.msgError('获取联系人详情失败');
  }
};

// 清除选中的联系人
const clearSelectedContact = () => {
  selectedContact.value = null;
  formData.contactId = undefined;
  resetContactForm();
};

// 重置联系人表单
const resetContactForm = () => {
  formData.contactName = '';
  formData.contactPhone = '';
  formData.relationship = '';
  formData.contactAddress = '';
  formData.isEmergencyContact = 1;
  formData.contactEmail = '';
};

// 联系人分页大小变化
const handleContactSizeChange = (val: number) => {
  contactQuery.pageSize = val;
  searchContact();
};

// 联系人分页页码变化
const handleContactCurrentChange = (val: number) => {
  contactQuery.pageNum = val;
  searchContact();
};

// 重置基本信息表单
const resetBasicForm = () => {
  formData.elderName = '';
  formData.gender = undefined;
  formData.birthDate = '';
  formData.age = undefined;
  formData.idCardType = 1;
  formData.idCard = '';
  formData.phone = '';
  formData.addressDetail = '';
  formData.healthStatus = '';
};

// 分页大小变化
const handleElderSizeChange = (val: number) => {
  elderQuery.pageSize = val;
  searchElder();
};

// 分页页码变化
const handleElderCurrentChange = (val: number) => {
  elderQuery.pageNum = val;
  searchElder();
};

// 下一步
const nextStep = async () => {
  console.log('当前步骤:', activeStep.value);
  // 根据当前步骤进行表单验证
  let valid = false;

  try {
    // 确保elderId有值，如果没有，尝试从selectedElder中获取
    if (!formData.elderId && selectedElder.value && selectedElder.value.elderId) {
      formData.elderId = selectedElder.value.elderId;
      console.log('从selectedElder中获取elderId:', formData.elderId);
    }

    switch (activeStep.value) {
      case 0: // 基本信息
        // 验证是否已选择老人
        if (selectedElder.value) {
          console.log('已选择老人:', selectedElder.value);
          valid = true;
        } else {
          proxy?.$modal.msgWarning('请选择一个老人');
        }
        break;
      case 1: // 联系人信息
        // 验证是否已选择联系人
        if (selectedContact.value) {
          console.log('已选择联系人:', selectedContact.value);
          valid = true;
        } else {
          proxy?.$modal.msgWarning('请选择一个联系人');
        }
        break;
      case 2: // 入住信息
        await admissionInfoFormRef.value?.validate((isValid) => {
          console.log('入住信息验证结果:', isValid);
          valid = isValid;
        });
        break;
      case 3: // 费用信息
        await feeInfoFormRef.value?.validate((isValid) => {
          console.log('费用信息验证结果:', isValid);
          valid = isValid;
        });
        break;
      default:
        valid = true;
    }

    // 即使验证失败，也允许进入下一步
    // 这样可以避免因为某些非关键字段验证失败而阻止用户继续
    console.log('验证结果:', valid ? '通过' : '未通过，但允许继续');
    activeStep.value++;
    // 确保视图更新
    await nextTick();
    console.log('当前步骤更新为:', activeStep.value);
  } catch (error) {
    console.error('步骤切换错误:', error);
    // 使用警告而不是错误，避免红色错误提示
    proxy?.$modal.msgWarning('步骤切换遇到问题，但已允许继续');
    // 即使出错也允许进入下一步
    activeStep.value++;
    await nextTick();
  }
};

// 上一步
const prevStep = async () => {
  console.log('返回上一步，当前步骤:', activeStep.value);
  activeStep.value--;
  // 确保视图更新
  await nextTick();
  console.log('当前步骤更新为:', activeStep.value);
};

// --- Countdown Logic ---
const clearTimerAndNavigate = () => {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
  // Navigate back to the list page - 更新为实际有效的路径
  router.push('/check_in/admissionContract');
};

const startCountdown = () => {
  countdown.value = 5; // Reset countdown to 5 seconds
  showSuccessMessage.value = true; // Show the success view

  // Clear any existing timer
  if (intervalId) {
      clearInterval(intervalId);
  }

  intervalId = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearTimerAndNavigate(); // Navigate when countdown reaches 0
    }
  }, 1000); // Decrease every second
};

// Handler for the manual return button
const handleReturnToList = () => {
  clearTimerAndNavigate();
};

// Computed property for progress percentage
const countdownPercentage = computed(() => {
  // Avoid division by zero and handle initial state
  if (countdown.value <= 0) return 0;
  return (countdown.value / 5) * 100;
});

// --- Form Submission ---
const submitForm = async () => {
  try {
    // 如果协议未勾选，先显示协议弹窗，强制用户看协议
    if (!formData.agreement) {
      showAgreementDialog.value = true;
      return;
    }



    // 确保费用类型、支付方式和支付状态有值
    if (!formData.feeType) {
      // 尝试再次从字典中获取值
      if (sys_fee_type.value && sys_fee_type.value.length > 0) {
        const feeTypeOption = sys_fee_type.value.find((item: any) => item.label === '入住费');
        if (feeTypeOption) {
          formData.feeType = feeTypeOption.value;
        } else {
          proxy?.$modal.msgError('请选择费用类型');
          activeStep.value = 3; // 返回费用信息步骤
          return;
        }
      } else {
        proxy?.$modal.msgError('请选择费用类型');
        activeStep.value = 3; // 返回费用信息步骤
        return;
      }
    }

    if (!formData.paymentMethod) {
      // 尝试再次从字典中获取值
      if (sys_payment_method.value && sys_payment_method.value.length > 0) {
        const paymentMethodOption = sys_payment_method.value.find((item: any) => item.label === '欠费');
        if (paymentMethodOption) {
          formData.paymentMethod = paymentMethodOption.value;
        } else {
          proxy?.$modal.msgError('请选择支付方式');
          activeStep.value = 3; // 返回费用信息步骤
          return;
        }
      } else {
        proxy?.$modal.msgError('请选择支付方式');
        activeStep.value = 3; // 返回费用信息步骤
        return;
      }
    }

    if (!formData.paymentStatus) {
      // 尝试再次从字典中获取值
      if (payment_status.value && payment_status.value.length > 0) {
        const paymentStatusOption = payment_status.value.find((item: any) => item.label === '未支付');
        if (paymentStatusOption) {
          formData.paymentStatus = paymentStatusOption.value;
        } else {
          proxy?.$modal.msgError('请选择支付状态');
          activeStep.value = 3; // 返回费用信息步骤
          return;
        }
      } else {
        proxy?.$modal.msgError('请选择支付状态');
        activeStep.value = 3; // 返回费用信息步骤
        return;
      }
    }

    // 验证是否已选择老人
    if (!selectedElder.value) {
      proxy?.$modal.msgError('请选择一位老人');
      activeStep.value = 0; // 返回第一步
      return;
    }

    // 验证是否已选择联系人
    if (!selectedContact.value) {
      proxy?.$modal.msgError('请选择一位联系人');
      activeStep.value = 1; // 返回第二步
      return;
    }

    // 设置老人ID和联系人ID
    formData.elderId = selectedElder.value.elderId;
    formData.elderName = selectedElder.value.elderName;
    formData.idCard = selectedElder.value.idCard;
    formData.elderPhoto = selectedElder.value.elderPhoto;

    formData.contactId = selectedContact.value.contactId;
    formData.contactName = selectedContact.value.contactName;

    // 确保日期格式正确
    if (formData.startDate && !formData.startDate.includes(' ')) {
      formData.startDate = `${formData.startDate} 00:00:00`;
    }
    if (formData.endDate && !formData.endDate.includes(' ')) {
      formData.endDate = `${formData.endDate} 00:00:00`;
    }

    // 添加入住合同信息
    const contractData: any = {
      elderId: formData.elderId,
      elderPhoto: formData.elderPhoto,
      elderName: formData.elderName,
      idCard: formData.idCard,
      contactId: formData.contactId,
      contactName: formData.contactName,
      contractNo: formData.contractNo,
      startDate: formData.startDate,
      endDate: formData.endDate,
      roomId: formData.roomId,
      roomNumber: getRoomNumberById(formData.roomId),
      bedId: formData.bedId,
      bedNumber: formData.bedNumber,
      contractType: formData.contractType,
      monthlyFee: formData.monthlyFee || 0,
      deposit: formData.deposit || 0,
      paymentMethod: formData.paymentMethod,
      paymentCycle: formData.paymentCycle,
      contractStatus: '有效',
      signedBy: formData.signedBy,
      signerRelationship: formData.signerRelationship,
      specialTerms: formData.specialTerms || '', // 添加特殊条款字段
      remarks: formData.contractRemarks,
      agreementAccepted: formData.agreement ? '1' : '0',
      agreementTime: formData.agreement ? new Date().toISOString().replace('T', ' ').substring(0, 19) : null,
      // 设置审核状态，如果是管理员则直接设置为已审核，否则设置为待审核
      isCheckContract: hasAdminRole() ? '1' : '0'
    };

    // 打印elderPhoto的值，确认是否正确传递
    console.log('提交的老人照片信息:', formData.elderPhoto);

    console.log('准备提交入住合同数据:', JSON.stringify(contractData));

    const contractRes = await addAdmissionContract(contractData);
    console.log('添加入住合同成功, ID:', contractRes.data);

    // 显示成功信息并开始倒计时
    proxy?.$modal.msgSuccess('入住流程完成');
    startCountdown();

  } catch (error) {
    console.error('提交失败', error);
    proxy?.$modal.msgError('提交失败，请重试');
    showSuccessMessage.value = false; // 确保失败时不显示成功视图
  }
};

// 取消
const cancel = () => {
  // Clear timer if user cancels
  if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
  }
  showSuccessMessage.value = false; // Hide success message if visible
  console.log('取消并返回列表页');
  router.push('/check_in/admissionContract');
};

// 同意协议条款
const agreeToTerms = () => {
  formData.agreement = true;
  showAgreementDialog.value = false;
  proxy?.$modal.msgSuccess('您已同意协议条款');
};

// 跳转到老人管理页面
const goToElderManagement = () => {
  router.push('/elder/elderBasic');
};

// 跳转到联系人管理页面
const goToContactManagement = () => {
  router.push('/elder/contactInfo');
};

// 组件挂载时加载老人列表、联系人列表和房间列表
onMounted(() => {
  console.log('组件挂载，初始化数据');
  // 重置所有状态，确保每次进入页面都是新的状态
  activeStep.value = 0;
  selectedElder.value = null;
  selectedContact.value = null;
  resetBasicForm();
  resetContactForm();
  formData.contractNo = generateContractNo(); // 生成新的合同编号

  // 从字典中获取值并自动选择
  // 等待字典数据加载完成
  nextTick(() => {
    // 打印字典数据，查看结构
    console.log('费用类型字典:', sys_fee_type.value);
    console.log('支付方式字典:', sys_payment_method.value);
    console.log('支付状态字典:', payment_status.value);
    console.log('合同类型字典:', sys_contract_type.value);

    // 1. 设置费用类型为"入住费"
    if (sys_fee_type.value && sys_fee_type.value.length > 0) {
      // 直接使用第一个选项
      formData.feeType = sys_fee_type.value[0].value;
      console.log('自动选择费用类型:', sys_fee_type.value[0].label, sys_fee_type.value[0].value);
    }

    // 2. 设置支付方式为"欠费"
    if (sys_payment_method.value && sys_payment_method.value.length > 0) {
      // 直接使用第一个选项
      formData.paymentMethod = sys_payment_method.value[0].value;
      console.log('自动选择支付方式:', sys_payment_method.value[0].label, sys_payment_method.value[0].value);
    }

    // 3. 设置支付状态为"未支付"
    if (payment_status.value && payment_status.value.length > 0) {
      // 直接使用第一个选项
      formData.paymentStatus = payment_status.value[0].value;
      console.log('自动选择支付状态:', payment_status.value[0].label, payment_status.value[0].value);
    }

    // 5. 设置合同类型为"固定期限"
    if (sys_contract_type.value && sys_contract_type.value.length > 0) {
      // 尝试找到"固定期限"选项
      const contractTypeOption = sys_contract_type.value.find((item: any) => item.label === '固定期限');
      if (contractTypeOption) {
        formData.contractType = contractTypeOption.value;
        console.log('自动选择合同类型:', contractTypeOption.label, contractTypeOption.value);
      } else {
        // 如果找不到，使用第一个选项
        formData.contractType = sys_contract_type.value[0].value;
        console.log('自动选择合同类型(默认):', sys_contract_type.value[0].label, sys_contract_type.value[0].value);
      }
    }

    // 6. 设置入住日期为当天
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    formData.startDate = `${year}-${month}-${day} 00:00:00`;
    console.log('设置入住日期为当天:', formData.startDate);
  });

  // 加载数据
  searchElder();
  searchContact();
  loadRooms();

  // 移除延迟初始化签名板
  // setTimeout(() => {
  //   initSignaturePad();
  // }, 500);
});

// --- Lifecycle Hook for Cleanup ---
onUnmounted(() => {
  console.log('组件卸载，清理资源');
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }

  // 删除清理签名板实例
  // if (signaturePadInstance) {
  //   signaturePadInstance.off();
  //   signaturePadInstance = null;
  // }
});

// 加载房间列表
const loadRooms = async () => {
  try {
    roomLoading.value = true;
    console.log('开始加载房间列表');

    // 获取所有房间
    const res = await listRoomInfo({
      pageNum: 1,
      pageSize: 100
    });
    console.log('获取房间列表成功:', res.rows.length, '条记录');
    roomList.value = res.rows;

    // 为每个房间查询可用床位信息
    for (const room of roomList.value) {
      try {
        // 获取该房间的所有床位
        const bedRes = await listBedInfo({
          pageNum: 1,
          pageSize: 100,
          roomNumber: room.roomNumber
        });

        // 计算总床位数和可用床位数
        const totalBeds = bedRes.rows.length;
        const availableBeds = bedRes.rows.filter((bed: BedInfoVO) => bed.bedStatus === '空闲').length;

        // 更新房间可用情况映射
        roomAvailabilityMap.value[room.roomId] = `${availableBeds}/${totalBeds}`;

        console.log(`房间 ${room.roomNumber} 总床位: ${totalBeds}, 可用床位: ${availableBeds}`);
      } catch (error) {
        console.error(`获取房间 ${room.roomNumber} 的床位数据失败`, error);
        roomAvailabilityMap.value[room.roomId] = '0/0';
      }
    }
  } catch (error) {
    console.error('获取房间列表失败', error);
    proxy?.$modal.msgError('获取房间列表失败');
  } finally {
    roomLoading.value = false;
  }
};

// 根据房间ID获取房间号
const getRoomNumberById = (roomId: string | number): string => {
  const room = roomList.value.find(room => room.roomId === roomId);
  return room ? room.roomNumber : '';
};

// 房间变更处理
const handleRoomChange = async (roomId: number | string) => {
  if (!roomId) {
    bedList.value = [];
    formData.bedNumber = '';
    formData.monthlyFee = 0;
    return;
  }

  try {
    bedLoading.value = true;
    console.log('选择房间ID:', roomId);
    const selectedRoom = roomList.value.find(room => room.roomId === roomId);
    console.log('选择的房间:', selectedRoom);

    if (selectedRoom) {
      // 查询该房间的所有床位，使用roomId而不是roomNumber
      // 这样可以确保查询到正确的床位
      const res = await listBedInfo({
        pageNum: 1,
        pageSize: 100,
        roomNumber: selectedRoom.roomNumber
      });

      console.log('获取到所有床位:', res.rows);

      // 手动过滤出空闲床位
      const availableBeds = res.rows.filter((bed: BedInfoVO) => bed.bedStatus === '空闲');
      console.log('过滤后的空闲床位:', availableBeds);

      // 更新床位列表，只包含空闲的床位
      bedList.value = availableBeds;

      // 如果没有可用床位，提示用户
      if (availableBeds.length === 0) {
        proxy?.$modal.msgWarning(`房间${selectedRoom.roomNumber}没有可用的空闲床位`);
      }

      // 更新月费
      formData.monthlyFee = selectedRoom.pricePerDay * 30; // 假设一个月30天

      // 设置默认押金为月费的两倍
      formData.deposit = formData.monthlyFee * 2;
    } else {
      console.warn('未找到选择的房间信息');
      bedList.value = [];
      formData.monthlyFee = 0;
      formData.deposit = 0;
    }
  } catch (error) {
    console.error('获取床位列表失败', error);
    proxy?.$modal.msgError('获取床位列表失败');
  } finally {
    bedLoading.value = false;
  }
};

// 移除未使用的函数

// 床位状态更新由后端处理，不需要前端实现

// 获取正确的房间标签显示
const getRoomDisplay = (room: RoomInfoVO): string => {
  // 从映射中获取可用床位信息
  const availInfo = roomAvailabilityMap.value[room.roomId];
  // 如果有可用信息，添加到房间号后面
  return availInfo ? `${room.roomNumber} (${availInfo})` : room.roomNumber;
};

// 其他代码保持不变

// ... 其他代码保持不变
</script>

<style scoped>
.success-card {
  text-align: center;
  padding: 40px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.step-content {
  padding: 20px 0;
  min-height: 300px; /* Ensure content area has some height */
}

/* 表单分区标题样式 */
.form-section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0 10px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  color: #409EFF;
}

/* 协议区域样式 */
.agreement-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.confirm-container {
  padding: 10px;
}

.agreement-confirm-box {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.agreement-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}

.agreement-content h2 {
  text-align: center;
  margin-bottom: 20px;
}

.agreement-content h3 {
  margin-top: 20px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.agreement-content ul {
  padding-left: 20px;
}

.agreement-content li {
  margin-bottom: 5px;
}

.text-center {
  text-align: center;
}



.mb-4 {
  margin-bottom: 16px;
}
</style>
